package com.cgsd.heyu.ui.home.fragment;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.android.library.utils.BeanUtils;
import com.android.library.utils.LogUtils;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.cgsd.heyu.App;
import com.cgsd.heyu.R;
import com.cgsd.heyu.ad.AdDrawVideo;
import com.cgsd.heyu.ad.AdFullVideo;
import com.cgsd.heyu.ad.AdListener;
import com.cgsd.heyu.ad.AdRewardVideo;
import com.cgsd.heyu.ad.AdSplash;
import com.cgsd.heyu.entity.AdContentEntity;
import com.cgsd.heyu.entity.RewardEntity;
import com.cgsd.heyu.entity.TaskEntity;
import com.cgsd.heyu.entity.VideoEntity;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.presenter.home.HomeContract;
import com.cgsd.heyu.presenter.home.HomePresenter;
import com.cgsd.heyu.ui.BaseFragment;
import com.cgsd.heyu.ui.common.TabActivity;
import com.cgsd.heyu.ui.video.JcvTrillVideo;
import com.cgsd.heyu.utils.AdUtils;
import com.cgsd.heyu.utils.UIUtils;
import com.danikula.videocache.HttpProxyCacheServer;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import fm.jiecao.jcvideoplayer_lib.JCMediaManager;
import fm.jiecao.jcvideoplayer_lib.VideotillManager;

public class TriListFragment extends BaseFragment implements HomeContract.VideoView {
    public static boolean IS_SCROLL_STATE_IDLE = true;
    public static boolean IS_SCROLL_STATE_SETTLING = false;
    boolean shareBack;
    private HomeContract.Presenter mPresenter;
    private RecyclerView mPager;
    private ListVideoAdapter videoAdapter;
    private List<VideoEntity> urlList = new ArrayList<>();
    private PagerSnapHelper snapHelper;
    private LinearLayoutManager layoutManager;
    private boolean isLoad;
    private int position = 0;
    //是否是刷新
    private boolean isRefresh;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            videoAdapter.notifyDataSetChanged();
            layoutManager.scrollToPosition(position);
            return true;
        }
    });
    private TextView tvTitle;
    private int mLable;

    private boolean isFirst = true;

    public TriListFragment() {
        // Required empty public constructor
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        JCMediaManager.addOnJcvdListener(null);
        VideotillManager.instance().releaseVideo();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_tri_list;
    }

    @Override
    public void onPause() {
        super.onPause();
        VideotillManager.instance().pause();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        LogUtils.i("sky", "onhidden=" + hidden);
        if (hidden) {
            VideotillManager.instance().pause();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        LogUtils.i("sky", "isVisibleToUser=" + isVisibleToUser);
        if (!isVisibleToUser) {
            VideotillManager.instance().pause();
        } else {
            if (isFirst) {
                View view = snapHelper.findSnapView(layoutManager);
                if (view == null) return;
                RecyclerView.ViewHolder viewHolder = mPager.getChildViewHolder(view);
                if (viewHolder != null && viewHolder instanceof VideoViewHolder) {
                    JcvTrillVideo video = ((VideoViewHolder) viewHolder).mp_video;
                    video.startVideo();
                }
            }
            isFirst = false;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!shareBack) {
            try {
//                VideotillManager.instance().play();
            } catch (Exception e) {
                showToast("视频播放错误");
            }
        } else {
            VideotillManager.instance().releaseVideo();
            JCMediaManager.instance().releaseMediaPlayer();
            handler.sendEmptyMessageDelayed(1, 500);
        }
        shareBack = false;
    }

    @Override
    protected void initView() {
        new HomePresenter(this);
        mPager = findViewById(R.id.rv_pager);
        snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(mPager);
        videoAdapter = new ListVideoAdapter(urlList);
        layoutManager = new LinearLayoutManager(requireActivity());
        mPager.setLayoutManager(layoutManager);
        mPager.setAdapter(videoAdapter);
        layoutManager.scrollToPosition(position);
    }

    @Override
    protected void initData() {
        addListener();
        isRefresh = true;
        mPresenter.getVideoList(page, 20);
    }

    private void addListener() {
        mPager.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private int position = -1;

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                int cur = layoutManager.findFirstVisibleItemPosition();
                if (cur != position) {
                    position = cur;
                    VideoEntity bean = urlList.get(cur);
                    mPresenter.statisticsVideoData(bean.getVideoId());
                }
            }
        });
        mPager.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) {
                LogUtils.i("sky", "onScrolled");
            }

            @Override
            public void onScrollStateChanged(@NotNull RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE://停止滚动
                        // todo 测试发现 SCROLL_STATE_DRAGGING 之后会回调一次 SCROLL_STATE_IDLE，但此时item并完全可见，
                        //  只有回调 SCROLL_STATE_SETTLING 之后在回调到的SCROLL_STATE_IDLE，item才算是完全可见，
                        //  因此我们需要在新增一个flag IS_SCROLL_STATE_SETTLING，
                        //  当IS_SCROLL_STATE_SETTLING为true时，才能将IS_SCROLL_STATE_IDLE置为true
                        if (IS_SCROLL_STATE_SETTLING) {
                            IS_SCROLL_STATE_IDLE = true;
                            IS_SCROLL_STATE_SETTLING = false;
                        }
                        if (urlList == null || urlList.size() == 0) {
                            return;
                        }

                        View view = snapHelper.findSnapView(layoutManager);
                        RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(view);
                        position = recyclerView.getChildLayoutPosition(view);

                        if (IS_SCROLL_STATE_IDLE) {
                            if (viewHolder != null && viewHolder instanceof VideoViewHolder) {
                                JcvTrillVideo video = ((VideoViewHolder) viewHolder).mp_video;
                                LogUtils.i("sky", "visible==" + isCurrentVisible());
                                if (isCurrentVisible()) {
                                    video.startVideo();
                                }
                            }
                        }

                        if (urlList.size() > position + 1) {
                            HttpProxyCacheServer proxy = App.getProxy(requireActivity());
                            proxy.getProxyUrl(urlList.get(position + 1).getVideoPlayUrl());
                        }

                        if (position > urlList.size() - 4) {
                            loadVideoData();
                        }
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:// 拖动
                        IS_SCROLL_STATE_IDLE = false;
                        IS_SCROLL_STATE_SETTLING = false;
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING:// 惯性滑动
                        IS_SCROLL_STATE_SETTLING = true;
                        IS_SCROLL_STATE_IDLE = false;
                        break;
                }
            }
        });
    }

    private boolean isCurrentVisible() {
        if (getActivity() instanceof TabActivity) {
            TabActivity activity = (TabActivity) getActivity();
            return activity.videoIsShow();
        }
        return false;
    }

    protected void loadVideoData() {
        if (!isLoad) {
            return;
        }
        isRefresh = false;
        page++;
        mPresenter.getVideoList(page, 10);
    }

    @Override
    public void setVideoData(List<VideoEntity> entities) {
        if (BeanUtils.isNotEmpty(entities)) {
            isLoad = true;
        } else {
            isLoad = false;
            return;
        }

        if (isRefresh) {
            urlList.addAll(entities);
            layoutManager = new LinearLayoutManager(requireActivity());
            mPager.setLayoutManager(layoutManager);
            mPager.setAdapter(new ListVideoAdapter(urlList));
            // layoutManager.scrollToPosition(position);
            // videoAdapter.notifyDataSetChanged();
        } else {
            if (entities.size() > 0) {
                urlList.addAll(entities);
                // videoAdapter.notifyDataSetChanged();
                // layoutManager.scrollToPosition(position);
            }
        }
        if (!urlList.isEmpty()) {
            for (int i = 0; i < urlList.size(); i++) {
                VideoEntity videoEntity = urlList.get(i);
                if (i % 4 == 1) {
                    videoEntity.setUserId("-1000");
                }
            }
        }

        layoutManager.scrollToPosition(position);
        videoAdapter.notifyDataSetChanged();

    }

    @Override
    public void taskRewordSuccess(RewardEntity entity) {
            if (entity == null) return;
        String awardFlower = entity.awardFlower;
        if (TextUtils.isEmpty(awardFlower)) return;
        showToast("积分 +"+awardFlower);
    }

    @Override
    public void setPresenter(HomeContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void setErrorMessage(ErrorMessage error) {
        handleErrorAction(error);
    }

    class ListVideoAdapter extends RecyclerView.Adapter<VideoViewHolder> {
        private List<VideoEntity> list;

        public ListVideoAdapter(List<VideoEntity> list) {
            this.list = list;
            Log.e("zx", "ListVideoAdapter: " + list.size());
        }

        @NonNull
        @Override
        public VideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(requireActivity()).inflate(R.layout.item_trill, parent, false);
            return new VideoViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull VideoViewHolder holder, int position) {
            VideoEntity bean = list.get(position);
            Log.e("zx", "onBindViewHolder: " + bean.getVideoPlayUrl());
            ViewGroup.LayoutParams layoutParams = holder.rootView.getLayoutParams();
            layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            holder.mp_video.updateDatas(bean);
            holder.mp_video.onNewShareListener(TriListFragment.this);
            holder.mp_video.setPosiont(position);
            holder.mp_video.setProgressListener(new JcvTrillVideo.PlayProgressListener() {
                @Override
                public void onPrepared() {
                    if (!isCurrentVisible()) {
                        VideotillManager.instance().pause();
                    }
                }
            });

            String userId = bean.getUserId();
            if ("-1000".equals(userId)) { // 嵌入 Draw ad
                holder.mp_video.setVisibility(View.GONE);
                holder.mAdContainer.setVisibility(View.VISIBLE);

                loadDrawVideoAd(holder.mAdContainer);
            } else {
                holder.mp_video.setVisibility(View.VISIBLE);
                holder.mAdContainer.setVisibility(View.GONE);

                if (position == TriListFragment.this.position) {
                    if (!isCurrentVisible()) {
                        holder.mp_video.pauseVideo();
                    } else {
                        holder.mp_video.startVideo();
                    }
                }
            }

        }


        @Override
        public int getItemCount() {
            return list.size();
        }

    }

    public class VideoViewHolder extends RecyclerView.ViewHolder {
        public View rootView;
        public JcvTrillVideo mp_video;
        public FrameLayout mAdContainer;

        public VideoViewHolder(View rootView) {
            super(rootView);
            this.rootView = rootView;
            this.mp_video = rootView.findViewById(R.id.mp_video);
            this.mAdContainer = rootView.findViewById(R.id.container);
        }
    }

    // TODO: 2021/4/20
    private void loadDrawVideoAd(FrameLayout mAdContainer) {
        AdContentEntity entity = new AdContentEntity("1", "946024371");
        AdDrawVideo adDrawVideo = new AdDrawVideo((Activity) mContext, entity, new AdDrawVideo.AdListener() {
            @Override
            public void onSuccess(View view) {
                if (view == null) return;
                mAdContainer.removeAllViews();
                mAdContainer.addView(view);
                Log.e("加载 ", "加载成功");
            }

            @Override
            public void onFail() {
                Log.e("加载 ", "加载失败");
                mAdContainer.removeAllViews();
            }

            @Override
            public void onVideoComplete(String codeId,int type) {
                if (type == -1|| TextUtils.isEmpty(codeId)) return;
                mPresenter.getTaskReword(codeId,type);
                Log.e("加载 ", "加载完成");

            }
        });

        adDrawVideo.loadAd();
    }
}